package com.htthorizon.gateway.handler;

import com.htthorizon.common.core.exception.LogCapcityOverException;
import com.htthorizon.system.api.exception.*;
import org.springframework.cloud.gateway.support.NotFoundException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import com.htthorizon.common.core.utils.ServletUtils;
import reactor.core.publisher.Mono;

/**
 * 网关统一异常处理
 *
 * @author mark
 */
@Order(-1)
@Configuration
public class GatewayExceptionHandler implements ErrorWebExceptionHandler
{
    private static final Logger log = LoggerFactory.getLogger(GatewayExceptionHandler.class);

    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex)
    {
        log.info("发生异常");
        ServerHttpResponse response = exchange.getResponse();

        if (exchange.getResponse().isCommitted())
        {
            return Mono.error(ex);
        }

        String msg;

        if (ex instanceof NotFoundException)
        {
            msg = "服务未找到";
        }
        else if (ex instanceof ResponseStatusException)
        {
            ResponseStatusException responseStatusException = (ResponseStatusException) ex;
            msg = responseStatusException.getMessage();
        }else if(ex instanceof MaxUserException){
            msg= "已达最大会话数";
        } else if (ex instanceof MultiTerminalLoginException) {
            msg= "多端登录";
        }else if (ex instanceof UnAllowAccessTimeException) {
            msg= "未在指定时间段登录";
        }else if (ex instanceof LogCapcityOverException) {
            msg= "日志超出配置容量大小";
        }else if (ex instanceof DownloadOverException) {
            msg= "下载数已超过阈值，请缩小范围";
        }else if (ex instanceof KeyNotException) {
            msg= "不允许重复访问或会话篡改";
        }else if (ex instanceof NotDeptException) {
            msg= "没有配置部门,请联系管理员";
        }
        else if (ex instanceof UserUnExistException) {
            msg= "用户未同步，或者用户被锁定";
        }else if (ex instanceof LogOverException) {
            msg= "日志容量超出配置最大上限，请联系管理员";
        }else if (ex instanceof BlackException) {
            msg= "此IP已被纳入黑名单";
        }else
        {
            msg = "内部服务器错误";
        }
        ex.printStackTrace();
        log.error("[网关异常处理]请求路径:{},异常信息:{}", exchange.getRequest().getPath(), msg);

        return ServletUtils.webFluxResponseWriter(response, msg);
    }
}